package club.janna.rpcdemo.server.codec;

import club.janna.rpcdemo.codec.Codec;
import club.janna.rpcdemo.domain.Request;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@ChannelHandler.Sharable
public class RPCDecoder extends ChannelInboundHandlerAdapter {
    private Codec codec;
    public RPCDecoder(Codec codec) { this.codec = codec; }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        buf.release();
        // 解析出请求
        Request request = codec.decode(bytes);
        // 传递到下一层
        ctx.fireChannelRead(request);
    }
}